package slidingWindow;

//https://leetcode.cn/problems/minimum-operations-to-reduce-x-to-zero/description/
public class l_1658 {
    public int minOperations(int[] nums, int x) {
        int n = nums.length, sum = 0, target = 0, res = 0, ans = -1;
        for(int i  = 0; i < n; ++i) sum += nums[i];
        target = sum - x;
        //这里可能x大于数组的和
        if(target < 0) return -1;
        //滑动窗口维护元素和, 这题可视为找和恰好为sum - x的最长连续子序列
        for(int left = 0, right = 0; right < n; ++right) {
            res += nums[right];
            while(res > target) res -= nums[left++];
            if(res == target) ans = Math.max(ans, right - left + 1);
        }
        return ans == -1 ? ans : n - ans;
    }
}
